package demo1;

import java.util.Arrays;

public class MyArrayList {
    private int[] elem ;
    private int usedSize ;
    private static final int DEFAULT_CAPACITY = 2;
    public MyArrayList(){
        this.elem = new int[DEFAULT_CAPACITY] ;
    }
    public MyArrayList(int initCapacity){
        this.elem = new int[initCapacity] ;
    }
    public void disPlay(){
        for(int i = 0 ; i< this.usedSize ; i++){
            System.out.print(this.elem[i] + "  ");
        }
    }
    public void add(int data){
           if(isFull()){
               // 扩容
               this.elem = Arrays.copyOf(this.elem ,
                       2* this.elem.length);
           }
        this.elem[this.usedSize] = data ;
        this.usedSize++ ;
    }
    public void add(int pos , int data){
        if(pos < 0 || pos > this.usedSize){
            throw new PosOutBoundsException(pos + " pos不合法") ;
        }
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem ,
                    2*this.elem.length) ;
        }
        for (int i = this.usedSize - 1 ; i >= pos ; i--) {
              this.elem[i + 1] = this.elem[i] ;
        }
        this.elem[pos] = data ;
        this.usedSize ++ ;
    }
    public boolean isFull(){
        if(this.usedSize == this.elem.length){
            return true ;
        }
        return false ;
    }
    public boolean contains(int toFind){
      for(int i = 0 ; i< this.usedSize ; i++){
          if(this.elem[i] == toFind){
              return true ;
          }
      }
      return false ;
    }
    public int indexOf(int toFind){
        for(int i = 0 ; i< this.usedSize ; i++){
            if(this.elem[i] == toFind){
                return i ;
            }
        }
        return -1 ;
    }
   public int get(int pos){
       if(pos < 0 || pos >= this.usedSize){
           throw new PosOutBoundsException(pos + " pos不合法") ;
       }
       return this.elem[pos] ;
   }
   public void set(int pos , int value){
       if(pos < 0 || pos >= this.usedSize){
           throw new PosOutBoundsException(pos + " pos不合法") ;
       }
       this.elem[pos] = value ;
   }

}
